package event;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * A utility class for logging and writing messages.
 * @author Charles
 *
 */
public class Logger {
	private OutputStream out;
	private DataOutputStream dos;
	
	protected int n;
	
	/**
	 * Creates a new logger that writes to an output stream.
	 * @param o the stream to which the new logger writes.
	 */
	public Logger(OutputStream o) {
		this.out = o;
		this.dos = new DataOutputStream(o);
		this.n = 0;
	}
	
	/**
	 * Gets this logger's stream.
	 * @return this logger's stream.
	 */
	public OutputStream getOutputStream() {
		return out;
	}
	
	/**
	 * Gets the number of messages that have been logged since this logger 
	 * was created or since the last time <code>resetCount()</code> was called 
	 * on this logger.
	 * @return the number of messages that have been logged since this logger 
	 * was created or since the last time <code>resetCount()</code> was called 
	 * on this logger.
	 */
	public int getCount() {
		return n;
	}
	
	/**
	 * Sets the stream to which this logger writes.
	 * @param o the stream to which this logger writes.
	 */
	public void setOutputStream(OutputStream o) {
		this.out = o;
		this.dos = new DataOutputStream(o);
	}
	
	/**
	 * Resets this logger's message count to zero.
	 */
	public void resetCount() {
		n = 0;
	}
	
	/**
	 * Logs a message. The message will be written to this logger's stream as soon the 
	 * stream allows.
	 * @param s the content of the message.
	 */
	public void logMsg(String s) {
		++n;
		writeToOutput(s);
	}
	
	protected void writeToOutput(final String s) {
		EventHandler.getEventHandler().accept(new Runnable() {
			@Override
			public void run() {
				try {
					if (out instanceof PrintStream) {
						((PrintStream)out).println(s);
					} else {
						dos.writeUTF(s + "\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * Flushes this logger's stream.
	 */
	public void flush() {
		try {
			dos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
